<template>
  <div class="SetPriceTableItemsHandle">
    <div>
      <span>销售单总额：￥{{ infoList.totalPrice || "0.00" }}</span>
    </div>
    <div class="mtb20">
      <span>关联产品：</span>
      <zm-button size="mini" class="ml5" @click="goSelect">
        选择产品
      </zm-button>
    </div>
    <!-- <div class="tr mr">
      <el-button class="mb20" type="primary" @click="handleAdd" size="mini">
        新增
      </el-button>
    </div> -->
    <Collapse v-for="(item, index) in infoList.list" :key="index" v-model="activeNames">
      <CollapseItem :name="index">
        <div slot="title" class="flex1">
          <div class="m-collapse-title ">
            <div class="flex1">
              <span>
                {{ "商品" + (index + 1) }}
              </span>
            </div>
            <div class="mr20">
              <i class="el-icon-delete fs20 mr10" :class="
                  infoList.list.length <= 1
                    ? 'info notAllow'
                    : 'primary pointer'
                " @click.stop="handelDel(index, infoList.list.length <= 1)"
></i>
            </div>
          </div>
        </div>
        <zm-form label-width="150px" :rules="rules" :model="item">
          <zm-form-item label="产品编号：" prop="productCode">
            {{item.productCode || '--'}}
          </zm-form-item>
          <zm-form-item label="产品名称：" prop="name">
            {{item.name || '--'}}
          </zm-form-item>
          <zm-form-item label="最低销售单价：" prop="minSalePrice">
            {{item.minSalePrice || '--'}}
          </zm-form-item>
          <zm-form-item label="运费：" prop="deliveryMoney">
            <zm-input v-model.trim="item.deliveryMoney" placeholder="请输入运费" :maxlength="50" class="w400" @input.native="limitInput($event, 'deliveryMoney', index)">
              <template slot="append">
                元
              </template>
            </zm-input>
          </zm-form-item>
          <el-form-item label="销售单价" prop="price">
            <zm-input type="number" v-model="item.price" placeholder="请输入销售单价" class="w400" @input.native="limitInput($event, 'price', index)">
              <template slot="append">
                元
              </template>
            </zm-input>
          </el-form-item>
          <el-form-item label="数量" prop="number">
            <zm-input type="number" v-model="item.number" placeholder="请输入销售数量" class="tc w400" @input.native="numberChange($event, 'number', index)">
              <template slot="append">
                份
              </template>
            </zm-input>
          </el-form-item>
          <el-form-item label="商品总额" prop="">
            ￥{{
              ((+item.price).toFixed(2) * (+item.number || 0) + +item.deliveryMoney).toFixed(2) || "0.00"
            }}
          </el-form-item>
        </zm-form>
      </CollapseItem>
    </Collapse>
    <div>
      <span class="vt">备注：</span>
      <zm-input v-model="infoList.remark" type="textarea" :maxlength="300" placeholder="请填写销售备注" class="w500">
      </zm-input>
    </div>
    <select-shiwu-product v-if="selectVisible" v-model="selectVisible" :product-info="infoList.list" @after-select="afterSelect" is-on-sale-order="1" is-form-sale>
    </select-shiwu-product>
</div>
</template>
<script>
import { Collapse, CollapseItem } from 'element-ui'
import SelectShiwuProduct from '@/views/product/physicalProductConfig/components/newProduct/components/selectShiwuProduct/index.vue'

export default {
  components: { Collapse, CollapseItem, SelectShiwuProduct },
  props: {
    rule: {
      type: Object,
      default: {}
    }
  },
  data () {
    return {
      activeNames: [0],
      Collapse,
      CollapseItem,
      selectVisible: false,
      rules: {
        productId: { required: true, message: '请填写', trigger: 'blur' },
        price: { required: true, message: '请填写', trigger: 'blur' },
        number: { required: true, message: '请填写', trigger: 'blur' }
      }
    }
  },
  computed: {
    infoList: {
      get () {
        return this.rule
      },
      set (val) {
        // this.rule = val
      }
    }

  },
  watch: {
    'infoList.list': {
      handler () {
        this.infoList.totalPrice = this.countTotal(this.infoList.list, 'price', 'number', 'deliveryMoney') || 0
      },
      deep: true
    }
  },
  created () { },
  methods: {
    countTotal (arr, keyPrice, keyNumber, keyExtend) {
      let $total = 0
      $total = arr.reduce(function (total, currentValue, currentIndex, arr) {
        return currentValue[keyPrice] && currentValue[keyNumber] ? (total + +(+currentValue[keyPrice] * +currentValue[keyNumber] + +currentValue[keyExtend]).toFixed(2)) : total
      }, 0)
      return $total.toFixed(2)
    },
    goSelect () {
      this.selectVisible = true
    },
    /* handleAdd () {
      this.infoList.list.push({
        name: '', //  商品名
        price: '', // 单价
        number: '' // 数量
      })
    }, */
    afterSelect (productInfo) {
      let info = JSON.parse(JSON.stringify(productInfo))
      let list = JSON.parse(JSON.stringify(this.infoList.list))

      const infoIds = info.map(item => item.id)
      const listIds = list.map(item => item.id)

      if (this.infoList.list.length > 0) {
        const _diffArr = listIds.filter(_i => { return !infoIds.includes(_i) })

        this.infoList.list = this.infoList.list.filter(item => {
          return !_diffArr.includes(item.id)
        })

        info.map(item => {
          if (listIds.includes(item.id)) {
            const tempObj = info.find(infoItem => {
              return infoItem.id === item.id
            })
            item = {
              id: item.id,
              productId: item.id,
              productCode: tempObj.productCode,
              name: tempObj.name,
              minSalePrice: tempObj.minSalePrice,
              deliveryMoney: item.deliveryMoney,
              price: item.price,
              number: item.number
            }
          } else {
            this.infoList.list.push(
              {
                id: item.id,
                productId: item.id,
                productCode: item.productCode,
                name: item.name,
                minSalePrice: item.minSalePrice,
                deliveryMoney: '',
                price: '',
                number: ''
              }
            )
          }
        })
      } else {
        info.map(item => {
          this.infoList.list.push(
            {
              id: item.id,
              productId: item.id,
              productCode: item.productCode,
              name: item.name,
              minSalePrice: item.minSalePrice,
              deliveryMoney: '',
              price: '',
              number: ''
            }
          )
        })
      }
    },
    handelDel (index, flag) {
      if (flag) {
        this.$message.warning('至少存在一个商品')
        return
      }
      this.$confirm('是否确定删除该商品', '提示', {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning'
      })
        .then(() => {
          this.infoList.list.splice(index, 1)
          this.$nextTick(() => {
            this.$message({
              message: '操作成功',
              type: 'success'
            })
          })
        })
        .catch(() => { })
    },
    limitInput (e, name, index) {
      this.infoList.list[index][name] =
        ('' + e.target.value)
          .replace(/[^\d^\\.]+/g, '')
          .replace(/^0+(\d)/, '$1')
          .replace(/^\./, '0.')
          .match(/^\d*(\.?\d{0,2})/g)[0] || ''
    },
    numberChange (e, key, index) {
      let regNumber = new RegExp('^[1-9][0-9]*$').test(e.target.value)
      if (key === 'number' && !regNumber) {
        // this.$message.warning('请输入正整数')
        this.$set(this.infoList.list[index], key, '')
      }
    }
  }
}
</script>
<style lang="scss">
.SetPriceTableItemsHandle {
  .m-collapse-title {
    font-size: 18px;
    color: #555;
    margin-bottom: 10px;
    width: 100%;
    display: flex !important;
    justify-content: center;
  }

  .el-collapse {
    border: none !important;
    margin-bottom: 10px !important;
  }

  .el-collapse-item__wrap {
    border-bottom: none;
  }

  .el-collapse-item:last-child {
    border: 1px solid #eee;
    padding: 10px 10px 0px 10px;
    box-sizing: border-box;
  }

  .el-collapse-item__header {
    border: none !important;
  }

  .el-collapse-item__arrow {
    margin-top: -9px !important;
  }
}
</style>
